//转义
var REGEXP_SINGLE_QUOTE = /'/g;
var REGEXP_LT = /</g;
var REGEXP_GT = />/g;
var REGEXP_QUOTE = /"/g;
function escapeHtmls (html) {
  return html.replace(REGEXP_LT, '').replace(REGEXP_GT, '').replace(REGEXP_QUOTE, '').replace(REGEXP_SINGLE_QUOTE, '');
}

//输入数据转义
function filters(elem) {
	var value = $(elem).val();
	var html = filterXSS(value, {
		whiteList:          [],        // 白名单为空，表示过滤所有标签
		stripIgnoreTag:     true,      // 过滤所有非白名单标签的HTML
		safeAttrValue: true,
		escapeHtml:escapeHtmls
	});
	$(elem).val(html);
}

//扩展Date的format方法 
Date.prototype.format = function (format) { 
var o = { 
"M+": this.getMonth() + 1, 
"d+": this.getDate(), 
"h+": this.getHours(), 
"m+": this.getMinutes(), 
"s+": this.getSeconds(), 
"q+": Math.floor((this.getMonth() + 3) / 3), 
"S": this.getMilliseconds() 
} 
if (/(y+)/.test(format)) { 
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); 
} 
for (var k in o) { 
if (new RegExp("(" + k + ")").test(format)) { 
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); 
} 
} 
return format; 
} 
/** 
*转换日期对象为日期字符串 
* @param date 日期对象 
* @param isFull 是否为完整的日期数据, 
* 为true时, 格式如"2000-03-05 01:05:04" 
* 为false时, 格式如 "2000-03-05" 
* @return 符合要求的日期字符串 
*/ 
function getSmpFormatDate(date, isFull) { 
var pattern = ""; 
if (isFull == true || isFull == undefined) { 
pattern = "yyyy-MM-dd hh:mm:ss"; 
} else { 
pattern = "yyyy-MM-dd"; 
} 
return getFormatDate(date, pattern); 
} 
/** 
*转换当前日期对象为日期字符串 
* @param date 日期对象 
* @param isFull 是否为完整的日期数据, 
* 为true时, 格式如"2000-03-05 01:05:04" 
* 为false时, 格式如 "2000-03-05" 
* @return 符合要求的日期字符串 
*/ 
function getSmpFormatNowDate(isFull) { 
return getSmpFormatDate(new Date(), isFull); 
} 
/** 
*转换long值为日期字符串 
* @param l long值 
* @param isFull 是否为完整的日期数据, 
* 为true时, 格式如"2000-03-05 01:05:04" 
* 为false时, 格式如 "2000-03-05" 
* @return 符合要求的日期字符串 
*/ 
function getSmpFormatDateByLong(l, isFull) { 
return getSmpFormatDate(new Date(l), isFull); 
} 
/** 
*转换long值为日期字符串 
* @param l long值 
* @param pattern 格式字符串,例如：yyyy-MM-dd hh:mm:ss 
* @return 符合要求的日期字符串 
*/ 
function getFormatDateByLong(l, pattern) { 
return getFormatDate(new Date(l), pattern); 
} 
/** 
*转换日期对象为日期字符串 
* @param l long值 
* @param pattern 格式字符串,例如：yyyy-MM-dd hh:mm:ss 
* @return 符合要求的日期字符串 
*/ 
function getFormatDate(date, pattern) { 
if (date == undefined) { 
date = new Date(); 
} 
if (pattern == undefined) { 
pattern = "yyyy-MM-dd hh:mm:ss"; 
} 
return date.format(pattern); 
} 

$(function () {
"use strict";
});

$.getUrlParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return  decodeURI(r[2]); return null;
}

//数组去重
Array.prototype.unique = function(){
	 this.sort(); //先排序
	 var res = [this[0]];
	 for(var i = 1; i < this.length; i++){
		 if(this[i] !== res[res.length - 1]){
			 res.push(this[i]);
	  	}
	 }
	 return res;
}

//数组去重
function unique(arr) {
    var result = [], isRepeated;
    for (var i = 0;i<arr.length;i++) {
        isRepeated = false;
        for (var j = 0;j<result.length;j++) {
            if (arr[i] == result[j]) {   
                isRepeated = true;
                break;
            }
        }
        if (!isRepeated) {
            result.push(arr[i]);
        }
    }
    return result;
}

$.ajaxSetup({
    cache:false, //关闭ajax缓存
    error:function(XMLHttpRequest,textStatus){
        if(XMLHttpRequest.status==200){
            return;
        }
        var sessionstatus=XMLHttpRequest.getResponseHeader("sessionstatus");
//        var repText=XMLHttpRequest.responseText;
//        var result=jQuery.parseJSON(repText);
        if(sessionstatus=="timeout"){
        	alert("温馨提示:您尚未登录，请前往登录");
        	window.location.replace(XMLHttpRequest.getResponseHeader("CONTEXTPATH"));
        }else if(XMLHttpRequest.status==403){  //验证不通过
            alert("权限不足");
        }else{
            alert("系统错误:请求出错,内部服务器出错");
        }

}
});

//判断是否为空
function isNull(value){
	  if(value==null){
		  return true;
	  }else if(value == 'undefined'){
		  return true;
	  }else if(value == undefined){
		  return true;
	  }else if(value == ""){
		  return true;
	  }else{
		  return false;
	  }
}

//过滤null 和 undefined值
function tranNull(value){
	  if(value==null){
		  return "";
	  }else if(value == 'undefined'){
		  return "";
	  }else if(value == undefined){
		  return "";
	  }else{
		  return value;
	  }
}

/**
 * 检验13,14,15,17,18 开头的手机号码
 * @param {} phoneStr: 号码串,逗号分隔  如: "131xxxxxxxx,131xxxxxxxx"
 */
function checkPhone (phoneStr) {
	if(!phoneStr.trim()){
		return false;
	}
	var phoneArr = phoneStr.split(/[,|，]/);
	var reg = /^1[3|4|5|6|7|8]\d{9}$/;
	for (i = 0; i < phoneArr.length; i++) {
		if (phoneArr[i] && !(reg.test(phoneArr[i]))) {
			return false;
		}
	}
	return true;
}

/**
 * 检验身份证号
 * add by lty
 * 
 * @param {} idStr: 身份证号
 */
function checkCardId (idStr) {
	if(!idStr.trim()){
		return false;
	}
	var _idReg = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/
	if (!_idReg.test(idStr)) {
		return false;
	}
	return true;
}

/**
 * 把上传的图片信息转成 图片url 的方法
 * add by lty
 * @param {} file 上传的图片信息
 */ 
function getObjectURL(file) {
  var url = null;
  if (window.createObjectURL != undefined) { // basic
     url = window.createObjectURL(file);
  } else if (window.URL != undefined) { // mozilla(firefox)
     url = window.URL.createObjectURL(file);
  } else if (window.webkitURL != undefined) { // webkit or chrome
     url = window.webkitURL.createObjectURL(file);
  }
  return url;
}


var bootstrap = {
	/**
	 * 提示框
	 * bootstrap.comfirn( "服务器宕机了",  function(){alert('点击了确认或关闭了窗口')} );
	 * */
	alert : function ( msg, callback) {
	    var dialogHTML = '<div id="selfAlert" class="modal fade" >';
		    dialogHTML += 	'<div class="modal-dialog" style="width: 80%; margin: 40% auto;">';
		    dialogHTML += 		'<div class="modal-content">';
		    dialogHTML += 			'<div class="modal-header"  style="border: 0px;">';
		    dialogHTML += 				'<button type="button" class="close" data-dismiss="modal" aria-label="Close">&times;</span></button>';
		    dialogHTML += 				'<h4 class="modal-title">' + '提示' + '</h4>';
		    dialogHTML += 			'</div>';
		    dialogHTML += 			'<div class="modal-body" style="text-align:center;">';
		    dialogHTML += 				msg||'';
		    dialogHTML += 			'</div>';
		    dialogHTML += 			'<div class="modal-footer" style="text-align:center; border:0px;">';
		    dialogHTML += 				'<button type="button" class="btn btn-primary" data-dismiss="modal">确定</button>';
		    dialogHTML += 			'</div>';
		    dialogHTML += 		'</div>';
		    dialogHTML += 	'</div>';
		    dialogHTML += '</div>';
	    if ($('#selfAlert').length <= 0) {
	        $('body').append(dialogHTML);
	    }
	    $('#selfAlert').on('hidden.bs.modal', function () {
	        $('#selfAlert').remove();
	        if (typeof callback == 'function') {
	            callback();
	        }
	    }).modal('show');
	},
	
	/**
	 * 确认框
	 * bootstrap.comfirn( "是否确认删库跑路",  function(){alert('点击了确认')},  function(){alert('点击了取消')}; );
	 * */
	comfirn : function ( msg, sure_callback, cancel_callback) {
        sure_callback = (typeof sure_callback=='function'?sure_callback+"()":"void(0)");
        cancel_callback = (typeof cancel_callback=='function'?cancel_callback+"()":"void(0)");		
	    var dialogHTML = '<div id="selfAlert" class="modal fade" >';
		    dialogHTML += 	'<div class="modal-dialog" style="width: 80%; margin: 40% auto;">';
		    dialogHTML += 		'<div class="modal-content">';
		    dialogHTML += 			'<div class="modal-header"  style="border: 0px;">';
		    dialogHTML += 				'<button type="button" class="close" data-dismiss="modal" aria-label="Close">&times;</span></button>';
		    dialogHTML += 				'<h4 class="modal-title">' + '提示' + '</h4>';
		    dialogHTML += 			'</div>';
		    dialogHTML += 			'<div class="modal-body" style="text-align:center;">';
		    dialogHTML += 				msg||'';
		    dialogHTML += 			'</div>';
		    dialogHTML += 			'<div class="modal-footer" style="text-align:center; border:0px;">';
		    dialogHTML += 				'<button type="button" class="btn btn-primary" data-dismiss="modal" onclick="'+sure_callback+'">确定</button>';
		    dialogHTML += 				'<button type="button" class="btn btn-primary" data-dismiss="modal" onclick="'+cancel_callback+'">取消</button>';
		    dialogHTML += 			'</div>';
		    dialogHTML += 		'</div>';
		    dialogHTML += 	'</div>';
		    dialogHTML += '</div>';
	    if ($('#selfAlert').length <= 0) {
	        $('body').append(dialogHTML);
	    }
	    $('#selfAlert').on('hidden.bs.modal', function () {
	        $('#selfAlert').remove();
	    }).modal('show');
	},
	
	
	/**
	 * 加载中
	 * var index = bootstrap.loading("处理中...");
	 * bootstrap.close(index);
	 * */
	loading : function ( msg ) {
		var width = msg? (msg.length<6 ? '' : msg.length*20) :50 ;
		var index = UUID();
    	var dialogHTML = '<div id="'+ index +'" class="modal fade" data-keyboard="false" data-backdrop="false" style="width: 100%;height: 100%; position: fixed; margin: 0;"  >';
    		dialogHTML += 	'<div class="modal-dialog" style="width: 100%;position: fixed;">';
		    dialogHTML += 		'<div class="loading modal-content" style="width:'+width+'px;">'+ (msg||'') +'</div>';
		    dialogHTML +=    '</div>';
		    dialogHTML += '</div>';
	    if ($('#'+index).length <= 0) {
	        $('body').append(dialogHTML);
	    }
	    $('#'+index).modal('show');
	    console.log(index);
	    return index;
	},
	
	close: function( index ){
		$('#'+index).modal('hide');
		$('#'+index).remove();
	},
	
}

function UUID() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; 
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); 
                                                        
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}


/**
 * 获取uuid
 */
function getUUID(){
	var d = new Date().getTime();
	var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
	  var r = (d + Math.random()*16)%16 | 0;
	  d = Math.floor(d/16);
	  return (c=='x' ? r : (r&0x3|0x8)).toString(16);
	});
	return uuid;
}
var common=({
	getUserInfo : function (){
		$.ajax({
			type : "POST",
			dataType : 'json',
			url : "../user/queryUserByOpenid.do",
			data : {
				"openid" : common.getCookie("openid")
			},
			success : function(data) {
				console.log(data);
				if(data.success){
					var flag="";
					if(data.user.flag==0) flag="租客";
					if(data.user.flag==1) flag="房东";
					if(data.user.flag==2) flag="管家";
					if(data.user.flag==3) flag="游客";
					if (data.user.nickName!=null) 
					{$("#name").html("");
					$("#name").text(data.user.nickName+"("+flag+")");}
					if (data.user.headImg!=null)
					{$("#headimg").attr("src",data.user.headImg);}
					if(data.user!=null){
						$("#loginout").show();
						$("#auth").show();
					}
					if(data.user!=null && data.user.openId!=null){
						$("#auth").hide();
					}
					if(data.user.flag==0){
						$("#myfoot").show();
					}
					if(data.user.flag==1){
						$("#homelist").show();
					}
				}else{
					window.location.href="../weixinImpl/login.do";
				}
			}
		});
		
	},
	getCookie : function (name) 
	{ 
	    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
	 
	    if(arr=document.cookie.match(reg))
	 
	        return unescape(arr[2]); 
	    else 
	        return null; 
	},
	timestampToTime :function (timestamp) {
	        var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
	        Y = date.getFullYear() + '-';
	        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
	        D = date.getDate(); 
	        return Y+M+D;
	    } 
})
